<template>
    <div class="user-project-manage-container">
      <el-card class="user-project-card" shadow="hover">
        <div class="header">
          <div class="title-section">
            <h2 class="page-title">
              <el-icon class="title-icon"><Connection /></el-icon>
              用户项目关联管理
            </h2>
            <p class="description">管理用户与项目的关联关系，分配用户到指定项目</p>
          </div>
          <el-button type="primary" @click="openDialog()" class="create-btn">
            <el-icon><Plus /></el-icon>
            创建关联
          </el-button>
        </div>
  
        <!-- 搜索和筛选区域 -->
        <div class="search-section">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户名或项目名称..."
            class="search-input"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="filterUserId" placeholder="选择用户" clearable @change="handleSearch">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.Username"
              :value="user.id"
            />
          </el-select>
          <el-select v-model="filterProjectId" placeholder="选择项目" clearable @change="handleSearch">
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.project_name"
              :value="project.id"
            />
          </el-select>
        </div>
  
        <!-- 用户项目关联表格 -->
        <el-table
          :data="filteredUserProjectList"
          stripe
          border
          class="user-project-table"
          v-loading="loading"
          empty-text="暂无关联数据"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column label="用户信息" min-width="180">
            <template #default="scope">
              <div class="user-info">
                <el-avatar :size="32" class="user-avatar">
                  {{ getUserNameById(scope.row.Userid)?.charAt(0)?.toUpperCase() || 'U' }}
                </el-avatar>
                <div class="user-details">
                  <div class="username">{{ getUserNameById(scope.row.Userid) || '未知用户' }}</div>
                  <div class="user-type">{{ getUserTypeById(scope.row.Userid) || '' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="项目信息" min-width="200">
            <template #default="scope">
              <div class="project-info">
                <el-icon class="project-icon"><Folder /></el-icon>
                <div class="project-details">
                  <div class="project-name">{{ getProjectNameById(scope.row.Porojectid) || getProjectTypeById(scope.row.Porojectid) || '未知项目' }}</div>
                  <div class="project-id">项目编号: {{ scope.row.Porojectid }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="urole" label="项目角色" min-width="120">
            <template #default="scope">
              <el-tag :type="getRoleTagType(scope.row.urole)" size="small">
                {{ scope.row.urole || '项目成员' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click="openDialog(scope.row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 用户项目关联创建/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑用户项目关联' : '创建用户项目关联'"
        width="600px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="user-project-form"
        >
          <el-form-item label="选择用户" prop="Userid">
            <el-select
              v-model="formData.Userid"
              placeholder="请选择用户"
              style="width: 100%"
              filterable
              clearable
            >
              <el-option
                v-for="user in availableUsers"
                :key="user.id"
                :label="`${user.Username} (${user.userType})`"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
  
          <el-form-item label="选择项目" prop="Porojectid">
            <el-select
              v-model="formData.Porojectid"
              placeholder="请选择项目"
              style="width: 100%"
              filterable
              clearable
            >
              <el-option
                v-for="project in availableProjects"
                :key="project.project_id"
                :label="`${project.project_name} (${project.state}) - ${project.project_id}`"
                :value="project.project_id"
              />
            </el-select>
          </el-form-item>
  
          <el-form-item label="项目角色" prop="urole">
            <el-select v-model="formData.urole" placeholder="请选择角色" style="width: 100%">
              <el-option label="项目经理" value="项目经理" />
              <el-option label="销售经理" value="销售经理" />
              <el-option label="项目成员" value="项目成员" />
              <el-option label="项目顾问" value="项目顾问" />
              <el-option label="项目观察者" value="项目观察者" />
            </el-select>
          </el-form-item>
  
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
  
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Connection,
  Plus,
  Search,
  Edit,
  Delete,
  Folder,
  User
} from '@element-plus/icons-vue'
import { 
  getUserProjectList, 
  createUserProject, 
  updateUserProject, 
  deleteUserProject 
} from '../api/userProject.js'
import { getUserList } from '../api/user.js'
import { getProjectList } from '../api/project.js'
import { formatDate } from '../utils/format.js'
  
  // 响应式数据
  const loading = ref(false)
  const submitting = ref(false)
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const searchKeyword = ref('')
  const filterUserId = ref('')
  const filterProjectId = ref('')
  const currentPage = ref(1)
  const pageSize = ref(20)
  const total = ref(0)
  
  // 数据列表
  const userProjectList = ref([])
  const userList = ref([])
  const projectList = ref([])
  
  // 表单数据
  const formRef = ref()
  const formData = reactive({
    Userid: '',
    Porojectid: '',
    urole: '项目成员',
    remark: ''
  })
  
  // 表单验证规则
  const formRules = {
    Userid: [
      { required: true, message: '请选择用户', trigger: 'change' }
    ],
    Porojectid: [
      { required: true, message: '请选择项目', trigger: 'change' }
    ],
    urole: [
      { required: true, message: '请选择角色', trigger: 'change' }
    ]
  }
  
  // 计算属性
  const filteredUserProjectList = computed(() => {
    let filtered = userProjectList.value
  
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      filtered = filtered.filter(item => {
        const userName = getUserNameById(item.Userid) || ''
        const projectName = getProjectNameById(item.Porojectid) || ''
        const projectType = getProjectTypeById(item.Porojectid) || ''
        return userName.toLowerCase().includes(keyword) || 
               projectName.toLowerCase().includes(keyword) ||
               projectType.toLowerCase().includes(keyword)
      })
    }
  
    if (filterUserId.value) {
      filtered = filtered.filter(item => item.Userid === filterUserId.value)
    }
  
    if (filterProjectId.value) {
      filtered = filtered.filter(item => item.Porojectid === filterProjectId.value)
    }
  
    return filtered
  })
  
  const availableUsers = computed(() => {
    // 过滤掉已经在当前项目中关联的用户
    if (isEdit.value && formData.Porojectid) {
      return userList.value.filter(user => {
        const existing = userProjectList.value.find(
          up => up.Userid === user.id && 
                up.Porojectid === formData.Porojectid && 
                up.id !== formData.id
        )
        return !existing
      })
    }
    return userList.value
  })
  
  const availableProjects = computed(() => {
    // 过滤掉当前用户已经关联的项目
    if (isEdit.value && formData.Userid) {
      return projectList.value.filter(project => {
        const existing = userProjectList.value.find(
          up => up.Userid === formData.Userid && 
                up.Porojectid === project.project_id && 
                up.id !== formData.id
        )
        return !existing
      })
    }
    return projectList.value
  })
  
  // 方法
  const loadUserProjectList = async () => {
    try {
      loading.value = true
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value
      }
     
      const response = await getUserProjectList(params)
      console.log(response)
      if (response) {
        userProjectList.value = response.records|| []
        total.value = response.total || 0
      } else {
        ElMessage.error(response.message || '获取用户项目关联列表失败')
      }
    } catch (error) {
      console.error('加载用户项目关联列表失败:', error)
      ElMessage.error('加载用户项目关联列表失败')
    } finally {
      loading.value = false
    }
  }
  
  const loadUserList = async () => {
    try {
     
      const params = { page: 1, pageSize: 1000 }
      const response = await getUserList(params)
      if (response) {
        userList.value = response.records|| []
      }
    } catch (error) {
      console.error('加载用户列表失败:', error)
    }
  }
  
  const loadProjectList = async () => {
    try {
      const params = { page: 1, pageSize: 1000 }
      const response = await getProjectList(params)
      //const response = await getProjectList()
      if (response) {
        projectList.value = response.records || []
      }
    } catch (error) {
      console.error('加载项目列表失败:', error)
    }
  }
  
  const openDialog = (row = null) => {
    if (row) {
      isEdit.value = true
      Object.assign(formData, row)
    } else {
      isEdit.value = false
      Object.assign(formData, {
        Userid: '',
        Porojectid: '',
        urole: '项目成员',
        remark: ''
      })
    }
    dialogVisible.value = true
  }
  
  const handleSubmit = async () => {
    try {
      await formRef.value.validate()
      submitting.value = true
  
      if (isEdit.value) {
        const response = await updateUserProject(formData.id, formData)
        if (response) {
          ElMessage.success('更新成功')
          dialogVisible.value = false
          loadUserProjectList()
        } else {
          ElMessage.error('更新失败')
        }
      } else {
        const response = await createUserProject(formData)
        if (response) {
          ElMessage.success('创建成功')
          dialogVisible.value = false
          loadUserProjectList()
        } else {
          ElMessage.error('创建失败')
        }
      }
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('操作失败')
    } finally {
      submitting.value = false
    }
  }
  
  const handleDelete = async (id) => {
    try {
      await ElMessageBox.confirm('确定要删除这个用户项目关联吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
  
      const response = await deleteUserProject(id)
     
        ElMessage.success('删除成功')
        loadUserProjectList()
     
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    }
  }
  
  const handleSearch = () => {
    currentPage.value = 1
  }
  
  const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    loadUserProjectList()
  }
  
  const handleCurrentChange = (page) => {
    currentPage.value = page
    loadUserProjectList()
  }
  
  // 辅助方法
  const getUserNameById = (userId) => {
    const user = userList.value.find(u => u.id === userId)
    return user ? user.Username : ''
  }
  
  const getUserTypeById = (userId) => {
    const user = userList.value.find(u => u.id === userId)
    return user ? user.userType : ''
  }
  
  const getProjectNameById = (projectId) => {
    const project = projectList.value.find(p => p.project_id === projectId)
    return project ? project.project_name : ''
  }
  
  const getProjectTypeById = (projectId) => {
    const project = projectList.value.find(p => p.project_id === projectId)
    return project ? project.project_type : ''
  }
  
  const getRoleTagType = (urole) => {
    const roleMap = {
      '项目经理': 'danger',
      '项目成员': 'primary',
      '项目顾问': 'warning',
      '项目观察者': 'info'
    }
    return roleMap[urole] || 'primary'
  }
  
  // 生命周期
  onMounted(() => {
    loadUserProjectList()
    loadUserList()
    loadProjectList()
  })
  </script>
  
<style scoped>
  .user-project-manage-container {
    padding: 0;
  }
  
  .user-project-card {
    margin-bottom: 20px;
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
  }
  
  .title-section {
    flex: 1;
  }
  
  .page-title {
    display: flex;
    align-items: center;
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
  }
  
  .title-icon {
    margin-right: 12px;
    font-size: 24px;
    color: #409EFF;
  }
  
  .description {
    margin: 0;
    color: #909399;
    font-size: 14px;
  }
  
  .create-btn {
    margin-left: 16px;
  }
  
  .search-section {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    align-items: center;
  }
  
  .search-input {
    flex: 1;
    max-width: 300px;
  }
  
  .user-project-table {
    margin-bottom: 24px;
  }
  
  .user-info {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .user-avatar {
    background: #409EFF;
    color: #fff;
    font-weight: 600;
  }
  
  .user-details {
    display: flex;
    flex-direction: column;
  }
  
  .username {
    font-weight: 600;
    color: #303133;
  }
  
  .user-type {
    font-size: 12px;
    color: #909399;
  }
  
  .project-info {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .project-icon {
    font-size: 20px;
    color: #409EFF;
  }
  
  .project-details {
    display: flex;
    flex-direction: column;
  }
  
  .project-name {
    font-weight: 600;
    color: #303133;
  }
  
  .project-id {
    font-size: 12px;
    color: #909399;
  }
  
  .pagination-section {
    display: flex;
    justify-content: center;
    margin-top: 24px;
  }
  
  .user-project-form {
    padding: 20px 0;
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
    }
    
    .search-section {
      flex-direction: column;
      align-items: stretch;
    }
    
    .search-input {
      max-width: none;
    }
    
    .create-btn {
      margin-left: 0;
      width: 100%;
    }
  }
  
  /* 表格样式优化 */
  .user-project-table .el-table__row:hover {
    background-color: #f5f7fa;
  }
  
  .user-project-table .el-table__cell {
    padding: 12px 0;
  }
  
  /* 标签样式 */
  .el-tag {
    border-radius: 4px;
    font-weight: 500;
  }
  
  /* 按钮样式 */
  .el-button {
    border-radius: 4px;
    font-weight: 500;
  }
  
  /* 输入框样式 */
  .el-input__inner,
  .el-textarea__inner {
    border-radius: 4px;
  }
  
  /* 选择器样式 */
  .el-select {
    width: 100%;
  }
  
  /* 日期选择器样式 */
  .el-date-editor {
    width: 100%;
  }
  
  /* 对话框样式 */
  .el-dialog {
    border-radius: 8px;
  }
  
  .el-dialog__header {
    border-bottom: 1px solid #ebeef5;
    padding: 20px 20px 15px;
  }
  
  .el-dialog__body {
    padding: 20px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #ebeef5;
    padding: 15px 20px 20px;
  }
  
  /* 卡片样式 */
  .user-project-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .user-project-card .el-card__body {
    padding: 24px;
  }
  
  /* 搜索区域样式 */
  .search-section {
    background: #fafafa;
    padding: 16px;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
  }
  
  /* 表格头部样式 */
  .user-project-table .el-table__header-wrapper {
    background: #f5f7fa;
  }
  
  .user-project-table .el-table__header th {
    background: #f5f7fa !important;
    color: #606266;
    font-weight: 600;
  }
  
  /* 分页样式 */
  .pagination-section .el-pagination {
    justify-content: center;
    margin-top: 20px;
  }
  
  /* 加载状态样式 */
  .el-loading-mask {
    background-color: rgba(255, 255, 255, 0.8);
  }
  
  /* 空数据样式 */
  .el-table__empty-block {
    padding: 40px 0;
  }
  
  .el-table__empty-text {
    color: #909399;
    font-size: 14px;
  }
  
  /* 操作按钮组样式 */
  .el-table .cell .el-button + .el-button {
    margin-left: 8px;
  }
  
  /* 表单验证样式 */
  .el-form-item.is-error .el-input__inner,
  .el-form-item.is-error .el-textarea__inner {
    border-color: #f56c6c;
  }
  
  .el-form-item__error {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    position: absolute;
    top: 100%;
    left: 0;
  }
  
  /* 头像样式优化 */
  .user-avatar {
    flex-shrink: 0;
  }
  
  /* 图标样式 */
  .title-icon,
  .project-icon {
    flex-shrink: 0;
  }
  
  /* 文本溢出处理 */
  .username,
  .project-name {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 120px;
  }
  
  /* 状态标签样式 */
  .el-tag--danger {
    background-color: #fef0f0;
    border-color: #fbc4c4;
    color: #f56c6c;
  }
  
  .el-tag--primary {
    background-color: #f0f9ff;
    border-color: #b3d8ff;
    color: #409eff;
  }
  
  .el-tag--warning {
    background-color: #fdf6ec;
    border-color: #f5dab1;
    color: #e6a23c;
  }
  
  .el-tag--info {
    background-color: #f4f4f5;
    border-color: #d3d4d6;
    color: #909399;
  }
  </style>